package features.advance.leetcode.tree.medium;

import features.advance.leetcode.tree.model.TreeNode;
import features.advance.leetcode.util.TreeUtil;

import java.util.*;

/**
 * @author Administrator
 * @date 2022-01-22 下午 4:33
 *
 * 面试题32 - I. 从上到下打印二叉树
 *
 * 难度：中等
 *
 * 从上到下打印出二叉树的每个节点，同一层的节点按照从左到右的顺序打印。
 *
 *
 *
 * 例如:
 * 给定二叉树: [3,9,20,null,null,15,7],
 *
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * 返回：
 *
 * [3,9,20,15,7]
 *
 *
 * 提示：
 *
 * 节点总数 <= 1000
 */
public class Solution32_1 {
    public static void main(String[] args) {
        Solution solution = new Solution() {
        };
        TreeNode<Integer> root = TreeUtil.parseArray("[3,9,20,null,null,15,7]");
        int[] ints = solution.levelOrder(root);
        System.out.println(Arrays.toString(ints));

    }

    static class Solution{
        public int[] levelOrder(TreeNode<Integer> root) {
            if(root == null){
                return new int[]{};
            }
            // 先进先出FIFO
            Queue<TreeNode<Integer>> queue = new LinkedList<>();
            queue.add(root);
            List<Integer> list = new ArrayList<>();
            while (!queue.isEmpty()){
                TreeNode<Integer> poll = queue.poll();
                list.add(poll.val);
                if(poll.left != null){
                    queue.add(poll.left);
                }
                if(poll.right != null){
                    queue.add(poll.right);
                }
            }
            int[] res = new int[list.size()];
            for (int i = 0; i < res.length; i++) {
                res[i] = list.get(i);
            }
            return res;
        }
    }
}
